package com.kexio.sms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.kexio.sms.impl.SmsServiceImpl;
import com.kexio.sms.impl.SmsVerificationServiceImpl;
import com.kexio.sms.service.SmsService;
import com.kexio.sms.service.SmsVerificationService;

/**
 * 短信服务自动配置
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@ConditionalOnProperty(prefix = "kexio.sms", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(SmsProperties.class)
@ComponentScan(basePackages = "com.kexio.sms")
public class SmsAutoConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsAutoConfiguration.class);
    
    /**
     * 短信服务Bean
     */
    @Bean
    @ConditionalOnMissingBean
    public SmsService smsService() {
        logger.info("注册短信服务: SmsServiceImpl");
        return new SmsServiceImpl();
    }
    
    /**
     * 短信验证码服务Bean
     */
    @Bean
    @ConditionalOnMissingBean
    public SmsVerificationService smsVerificationService() {
        logger.info("注册短信验证码服务: SmsVerificationServiceImpl");
        return new SmsVerificationServiceImpl();
    }
    
    /**
     * 短信服务启动日志
     */
    @Bean
    public SmsStartupLogger smsStartupLogger(SmsProperties properties) {
        return new SmsStartupLogger(properties);
    }
    
    /**
     * 启动日志组件
     */
    public static class SmsStartupLogger {
        
        private final SmsProperties properties;
        
        public SmsStartupLogger(SmsProperties properties) {
            this.properties = properties;
            logStartupInfo();
        }
        
        private void logStartupInfo() {
            logger.info("========================================");
            logger.info("📱 Kexio SMS Service 启动成功!");
            logger.info("🔧 服务配置:");
            logger.info("   默认提供商: {}", properties.getDefaultProvider());
            logger.info("   备用提供商: {}", properties.getFallbackProvider());
            logger.info("   故障转移: {}", properties.isEnableFailover() ? "✅ 启用" : "❌ 禁用");
            logger.info("📝 验证码配置:");
            logger.info("   默认长度: {}位", properties.getVerification().getDefaultLength());
            logger.info("   默认有效期: {}分钟", properties.getVerification().getDefaultExpireMinutes());
            logger.info("   最大验证次数: {}次", properties.getVerification().getMaxVerifyCount());
            logger.info("🛡️ 限流配置:");
            logger.info("   限流开关: {}", properties.getRateLimit().isEnabled() ? "✅ 启用" : "❌ 禁用");
            if (properties.getRateLimit().isEnabled()) {
                logger.info("   发送间隔: {}秒", properties.getRateLimit().getSendIntervalSeconds());
                logger.info("   每小时限制: {}条/手机号", properties.getRateLimit().getMaxSendPerHourPerPhone());
                logger.info("   每日限制: {}条/手机号", properties.getRateLimit().getMaxSendPerDayPerPhone());
            }
            logger.info("📊 记录配置:");
            logger.info("   发送记录: {}", properties.getRecord().isEnabled() ? "✅ 启用" : "❌ 禁用");
            logger.info("   记录保留: {}天", properties.getRecord().getRetentionDays());
            logger.info("   自动清理: {}", properties.getRecord().isAutoCleanup() ? "✅ 启用" : "❌ 禁用");
            
            // 服务提供商配置检查
            logger.info("📡 服务提供商配置:");
            checkProviderConfig("阿里云", properties.getAliyun().getAccessKeyId(), properties.getAliyun().getSignName());
            checkProviderConfig("腾讯云", properties.getTencent().getSecretId(), properties.getTencent().getSignName());
            checkProviderConfig("华为云", properties.getHuawei().getAccessKey(), properties.getHuawei().getSignName());
            
            logger.info("🚀 短信服务已就绪!");
            logger.info("========================================");
        }
        
        private void checkProviderConfig(String providerName, String accessKey, String signName) {
            boolean hasConfig = accessKey != null && !accessKey.trim().isEmpty() && 
                              signName != null && !signName.trim().isEmpty();
            logger.info("   {}: {}", providerName, hasConfig ? "✅ 已配置" : "❌ 未配置");
        }
    }
}
